package cn.infinite.security.core.impl;

import cn.easier.club.base.pool.HttpClientPoolManager;
import cn.infinite.security.configuration.WxConfigurerProperties;
import cn.infinite.security.core.WxAuthenticateAble;
import cn.infinite.security.core.WxUserService;
import cn.infinite.security.error.WxAuthenticationException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Optional;

@Slf4j
@AllArgsConstructor
public class DefaultWxAuthenticateService implements WxAuthenticateAble {

    private WxUserService wxUserService;

    private HttpClientPoolManager httpClientPoolManager;

    private WxConfigurerProperties wxConfigurerProperties;

    @Override
    public UserDetails authenticateByWxCode(String code) throws AuthenticationException {
        //调用微信接口获取获取openId
        String openId = "";
        //调用微信认证服务获取用户信息
        try {
            Optional<UserDetails> userDetailsOptional = this.wxUserService.findUserDetailByOpenId(openId);
            return userDetailsOptional.orElseGet(() -> {
                try {
                    UserDetails userDetails = this.wxUserService.registerUserByOpenId(openId, "");
                    return userDetails;
                } catch (Exception e) {
                    log.error("auto register user error", e.getMessage());
                    return null;
                }
            });
        } catch (Exception e) {
            log.error("wx code authenticate error", e.getMessage());
            throw new WxAuthenticationException(e.getMessage());
        }
    }
}
